package org.example;

import org.example.AppConfig;
import org.example.TimerTaskService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

public class App {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 1. 创建基于注解的Spring IOC容器
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

        // 2. 获取线程池和任务服务
        ThreadPoolExecutor executor = context.getBean("threadPoolExecutor", ThreadPoolExecutor.class);
        TimerTaskService taskService = context.getBean(TimerTaskService.class);

        System.out.println("=== Spring IOC容器启动成功 ===");
        System.out.println("线程池状态: " + executor.toString());

        // 3. 执行多个任务
        System.out.println("\n=== 开始执行多个任务 ===");

        // 执行每秒输出时间任务（持续10秒）
        CompletableFuture<Void> timeTask = taskService.printCurrentTimeEverySecond(10);

        // 执行倒计时任务（60秒）
        CompletableFuture<Void> countdownTask = taskService.countdownTask(10);

        // 执行计算任务
        CompletableFuture<Long> calculationTask = taskService.calculateFactorial(8);

        // 等待所有任务完成
        CompletableFuture.allOf(timeTask, countdownTask, calculationTask).get();

        // 获取计算结果
        Long factorialResult = calculationTask.get();
        System.out.println("最终计算结果: " + factorialResult);

        // 4. 显示线程池最终状态
        System.out.println("\n=== 任务执行完成 ===");
        System.out.println("线程池最终状态: " + executor.toString());

        // 5. 优雅关闭线程池
        executor.shutdown();
        System.out.println("应用程序结束");
    }
}
